/*
    Copyright (c) 2011, Alex Brombal
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Brombal, LLC nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "lib-netio.h"
#include <stdio.h>
#include <errno.h>


void * nthread(void *);
bool _nopen_wait(nconn * conn);
ssize_t _nread(nconn * conn, void * buf, size_t len, int opt);
void _nerrorchk(nconn * conn);
void _nclosed(nconn * conn);


nconn * nopen(const char * host, u_int16_t port, u_int16_t timeout, ncallbacks cb)
{
    errno = 0;
    
    nconn * conn = (nconn *)malloc(sizeof(nconn));
    
    conn->host = (char *)malloc(strlen(host));
    
    strcpy(conn->host, host);
    
    conn->open = false;
    
    conn->port = port;
    conn->timeout = timeout;
    
    conn->pthread = NULL;
    
    memcpy(&conn->cb, &cb, sizeof(ncallbacks));

    _nerrorchk(conn);
    
    // Create socket
    conn->socket = socket(AF_INET, SOCK_STREAM, 0);
    if(conn->socket < 0) goto fail;
    
    // Get server info
    conn->server = malloc(sizeof(struct hostent));
    struct hostent * server = gethostbyname(host);
    if(server == NULL) goto fail;
    memcpy(conn->server, server, sizeof(struct hostent));
    
    // Create Internet socket address
    memset(&conn->serv_addr, 0, sizeof(conn->serv_addr)); 
    conn->serv_addr.sin_family = AF_INET;
    conn->serv_addr.sin_port = htons(port);
    memcpy(&conn->serv_addr.sin_addr, conn->server->h_addr_list[0], conn->server->h_length);
    
    // Make the connection non-blocking
    fcntl(conn->socket, F_SETFL, O_NONBLOCK);
    _nerrorchk(conn);
    
    // Make the connection
    connect(conn->socket, (struct sockaddr *)&(conn->serv_addr), sizeof(conn->serv_addr));
    if(errno == EINPROGRESS) errno = 0;
    _nerrorchk(conn);
    
    if(conn->cb.open || conn->cb.read || conn->cb.close)
    {
        // Start a thread to listen for events
        pthread_create(&conn->pthread, NULL, nthread, conn);
        return conn;
    }
    else
    {
        // Wait for readiness (blocking)
        if(_nopen_wait(conn)) return conn;
    }
    
    // If it got here, it failed, so free nconn and return null
fail:
    _nerrorchk(conn);
    return NULL;
}


void * nthread(void * c)
{
    nconn * conn = (nconn *)c;
    
    if(!conn->open)
        if(!_nopen_wait(conn)) return NULL;
    
    while(true)
    {
        if(conn->error) break;
        if(!conn->open) break;
        
        fd_set fdset;
        FD_ZERO(&fdset);
        FD_SET(conn->socket, &fdset);
        int s = select(conn->socket+1, &fdset, NULL, NULL, &(struct timeval){ 1, 0 });
        if(s > 0)
        {
            ssize_t r = recv(conn->socket, &(char){0}, 1, MSG_PEEK);
            if(r > 0)
            {
                if(conn->cb.read) conn->cb.read(conn);
            }
            else
            {
                if(errno == ECONNRESET) _nclosed(conn);
                else _nerrorchk(conn);
            }
        }
        else if(s < 0) _nerrorchk(conn);
    }
    return NULL;
}


inline bool _nopen_wait(nconn * conn)
{
    fd_set fdset;
    FD_ZERO(&fdset);
    FD_SET(conn->socket, &fdset);
    int s = select(FD_SETSIZE, NULL, &fdset, NULL, &(struct timeval){ conn->timeout, 0 });
    if(s > 0)
    {
        conn->open = true;
        if(conn->cb.open) conn->cb.open(conn);
        return true;
    }
    else
    {
        conn->open = false;
        _nerrorchk(conn);
        if(!conn->error) {
            conn->error = ETIMEDOUT;
            if(conn->cb.error) conn->cb.error(conn);
        }
        return false;
    }
}


inline ssize_t nread(nconn * conn, void * buf, size_t len) { return _nread(conn, buf, len, 0); }
inline ssize_t npeek(nconn * conn, void * buf, size_t len) { return _nread(conn, buf, len, MSG_PEEK); }

ssize_t _nread(nconn * conn, void * buf, size_t len, int opt)
{
    errno = 0;
    fd_set fdset;
    FD_ZERO(&fdset);
    FD_SET(conn->socket, &fdset);
    int s = select(conn->socket+1, &fdset, NULL, NULL, &(struct timeval){ 1, 0 });
    if(s > 0)
    {
        ssize_t r = recv(conn->socket, buf, len, opt);
        if(r > 0) return r;
        else if(!errno || errno == ETIMEDOUT) _nclosed(conn);
        else _nerrorchk(conn);
    }
    else if(s < 0) _nerrorchk(conn);
    return 0;
}



ssize_t nwrite(nconn * conn, const char * data, size_t len)
{
    errno = 0;
    ssize_t w = send(conn->socket, data, len, MSG_EOF);
    _nerrorchk(conn);
    return w;
}



void _nclosed(nconn * conn)
{
    conn->open = false;
    if(conn->cb.close) conn->cb.close(conn);
}


void nclose(nconn * conn)
{
    free(conn->host);
    free(conn->server);
    free(conn);
}

void _nerrorchk(nconn * conn)
{
    if(!errno) return;
    conn->error = errno;
    errno = 0;
    if(conn->cb.error) conn->cb.error(conn);
}


void nwait(nconn * conn)
{
    if(conn->pthread) pthread_join(conn->pthread, NULL);
}

